package com.whf.security.browser;

import com.whf.security.browser.Authentication.MyAuthenticationSuccessHandler;
import com.whf.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * security提供的一个适配器类,做web安全配置的适配器
 * 1.覆盖configure方法
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    //将登陆成功处理接口注入自定义的处理类(还需要将其添加到successHandeler配置中)
    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()                //指定使用表单验证,.httpBasic()是弹出默认登录窗口
                .loginPage("/authentication/require")   //指定登陆页面网址(注意一定要将该url放入非授权验证中)
                .loginProcessingUrl("/authentication/form")  //验证表单提交路径,配置后security会通知usernamepassword**Filter去验证
                .successHandler(myAuthenticationSuccessHandler) //登陆成功处理器
                .failureHandler(myAuthenticationFailHandler)   //登陆失败处理器
                .and()
                .authorizeRequests()        //以下是授权配置
                .antMatchers("/authentication/require", securityProperties.getBrowser().getLoginPage()).permitAll()    //将登陆的url排除在外,其余的全部处理
                .anyRequest()               //对所有请求进行下面的操作
                .authenticated()         //进行授权验证
                .and()
                .csrf().disable();      //关闭csrf攻击防护

    }


    //开启密码加密功能,该接口中由两个方法
    //方法1:encode()对密码加密
    //方法2:matches()验证密码是否正确,改方法security自动调用
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();

    }


}
